/*
 * Copyright (C) 2008 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.dtr.zxing.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.google.zxing.Result;
import com.yh.autobio.AppConfig;
import com.yh.autobio.AppContext;
import com.yh.autobio.R;
import com.yh.autobio.base.BaseActivity;
import com.yh.autobio.common.StringUtils;
import com.yh.autobio.common.UIHelper;
import com.yh.autobio.component.dialog.DialogHelp;
import com.dtr.zxing.utils.CaptureActivityHandler;
import com.dtr.zxing.utils.InactivityTimer;
import com.yh.autobio.modules.bean.BarCode;
import com.yh.autobio.modules.bean.CKComp;
import com.yh.autobio.modules.bean.CKInfo;
import com.yh.autobio.modules.bean.User;
import com.yh.autobio.modules.widget.dragexpandgrid.BadgeView;

import java.lang.reflect.Field;
import java.util.ArrayList;

import static com.yh.autobio.AppConfig.SCN_CUST_ACTION_SCODE;

/**
 * This activity opens the camera and does the actual scanning on a background
 * thread. It draws a viewfinder to help the user place the barcode correctly,
 * shows feedback as the image processing is happening, and then overlays the
 * results when a scan is successful.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 * @author Sean Owen
 */
public final class CaptureActivity extends BaseActivity
        {

    private static final String TAG = CaptureActivity.class.getSimpleName();

//    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private InactivityTimer inactivityTimer;
//    private BeepManager beepManager;
//    private SurfaceView scanPreview = null;
//    private RelativeLayout scanContainer;
//    private RelativeLayout scanCropView;
//    private ImageView scanLine;
//    private TextView tv_sacan_faild;
    private ImageView mFlash,iv_count;
    private BadgeView mBvNotice_tweet;
//    private Rect mCropRect = null;
    private ArrayList<CKComp> cmps;
    private  String userType;
    private String workno;

    private ArrayList<CKInfo> checkedCKS;
    public Handler getHandler() {
        return handler;
    }

    private BroadcastReceiver mSamDataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SCN_CUST_ACTION_SCODE)) {
                String message = intent.getStringExtra(AppConfig.SCN_CUST_EX_SCODE);
                handleOtherText(message);
            }
        }
    };

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_qr_scan);

        iv_count = (ImageView) findViewById(R.id.iv_count);

        mFlash = (ImageView) findViewById(R.id.capture_flash);
        mFlash.setOnClickListener(this);
        iv_count.setOnClickListener(this);

        cmps=new ArrayList<>();
        mBvNotice_tweet = new BadgeView(CaptureActivity.this, iv_count);
        mBvNotice_tweet.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
        mBvNotice_tweet.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
        mBvNotice_tweet.setBackgroundResource(R.drawable.notification_bg);
        mBvNotice_tweet.setGravity(Gravity.CENTER);
        IntentFilter intentFilter = new IntentFilter(SCN_CUST_ACTION_SCODE);
        registerReceiver(mSamDataReceiver, intentFilter);
        inactivityTimer = new InactivityTimer(this);



        User user=AppContext.getInstance().getCurrentUser();
        if (user!=null) {
            userType = user.getDuty();
            if (!StringUtils.isEmpty(userType)) {
                if ("车间工人".equals(userType) || "仓库管理".equals(userType)){

                }else {
                    Snackbar.make(mFlash, "员工类型非车间工人或者仓库管理，不允许扫码操作", Snackbar.LENGTH_SHORT).show();
                    CaptureActivity.this.finish();
                }
            }else {
                Snackbar.make(mFlash, "未定义的员工类型，不允许扫码操作", Snackbar.LENGTH_SHORT).show();
                CaptureActivity.this.finish();
            }
        }

        Intent mExaIntent=getIntent();
        if (mExaIntent!=null) {
            Bundle args = mExaIntent.getExtras();
            if (args!=null){
                workno=  args.getString("workno");
                checkedCKS= (ArrayList<CKInfo>) args.getSerializable("checkedCKS");
            }
        }
    }

    /**
     * 刷新已扫描到的入库单
     */
    public void updateUnreadLabel_tweet() {
        int count = cmps.size();
        if (count > 0) {
            mBvNotice_tweet.setText(count + "");
            mBvNotice_tweet.show();
        } else {
            mBvNotice_tweet.hide();
        }
    }

    @SuppressLint("NewApi")
    @Override
    protected boolean hasActionBar() {

        if (android.os.Build.VERSION.SDK_INT >= 11) {
//            getSupportActionBar().hide();
            return true;
        } else {
            return false;
        }

    }



    @Override
    protected void onDestroy() {
        if (inactivityTimer!=null) {
            inactivityTimer.shutdown();
        }
        unregisterReceiver(mSamDataReceiver);
        super.onDestroy();
    }

    /**
     * A valid barcode has been found, so give an indication of success and show
     * the results.
     *
     * @param rawResult The contents of the barcode.
     * @param bundle    The extras
     */
    public void handleDecode(final Result rawResult, Bundle bundle) {
        inactivityTimer.onActivity();

        // 通过这种方式可以获取到扫描的图片
//	bundle.putInt("width", mCropRect.width());
//	bundle.putInt("height", mCropRect.height());
//	bundle.putString("result", rawResult.getText());
//
//	startActivity(new Intent(CaptureActivity.this, ResultActivity.class)
//		.putExtras(bundle));

        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                handleText(rawResult.getText());
            }
        }, 800);
    }

    private void handleText(String text) {

        if (StringUtils.isUrl(text)) {
//            showUrlOption(text);
        } else {
            handleOtherText(text);
        }
    }

    private void showConfirmLogin(final String url) {
        if (!AppContext.getInstance().isLogin()) {
            showLogin();
            return;
        }
        DialogHelp.getConfirmDialog(this, "扫描成功，是否进行网页登陆", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
//                handleScanLogin(url);
                finish();
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish();
            }
        }).show();
    }

    private void handleOtherText(final String text) {
        // yhzw#gxhb#Work43
        String[] sp=text.split("#");
        if (sp!=null) {
            if (sp.length >= 3) {
                if (sp[0].equals("yhzw")){
                    switch (sp[1]) {
                        case "gxhb":
                            if ("车间工人".equals(userType)) {
                                iv_count.setVisibility(View.GONE);
                                UIHelper.showWorks(this, sp[2]);
                            }else {
                                Snackbar.make(mFlash, "员工类型非车间工人，不允许工序扫码操作", Snackbar.LENGTH_SHORT).show();
                            }
                            break;
                        case "ck":
                            if ("仓库管理".equals(userType)) {
                                if (sp.length == 6) {
                                    int mcount=Integer.parseInt(sp[3]);
                                        if (cmps.size()==0){
                                            CKComp cm = new CKComp();
                                            cm.setCount(Integer.parseInt(sp[3]));
                                            cm.setItemDN(sp[4]);
                                            cm.setType(sp[5]);
                                            if (mcount==1){
                                                cm.setAll(true);
                                            }
                                            cmps.add(cm);
                                        }else {
                                            for (int m = 0; m < cmps.size(); m++) {
                                                CKComp outcp = cmps.get(m);
                                                String outype = outcp.getType();
                                                String outid = outcp.getItemDN();
                                                if (sp[5].equals(outype) && sp[4].equals(outid)) {
                                                    Snackbar.make(mFlash, "已经扫描过了！", Snackbar.LENGTH_SHORT).show();
                                                    m = cmps.size();
                                                } else if (sp[4].equals(outid) && !sp[5].equals(outype)) {
                                                    outcp.setAll(true);
                                                    Snackbar.make(mFlash, "主副门已经全部扫描过了！", Snackbar.LENGTH_SHORT).show();
                                                }else if (!sp[4].equals(outid)){
                                                    if (m == cmps.size() - 1) {
                                                        if (!sp[4].equals(outid)) {
                                                            CKComp cm = new CKComp();
                                                            cm.setCount(Integer.parseInt(sp[3]));
                                                            cm.setItemDN(sp[4]);
                                                            cm.setType(sp[5]);
                                                            if (mcount==1){
                                                                cm.setAll(true);
                                                            }
                                                            cmps.add(cm);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        if (cmps.size()>0){
                                            iv_count.setVisibility(View.VISIBLE);
                                        }
                                        updateUnreadLabel_tweet();

                                    }
                                } else {
                                    Snackbar.make(mFlash, "错误的出入库二维码！", Snackbar.LENGTH_SHORT).show();

                                }
                            break;
                        default:
                            Snackbar.make(mFlash, "未定义的操作类型", Snackbar.LENGTH_SHORT).show();

                            break;
                    }
                } else {
                    Snackbar.make(mFlash, "错误的条码", Snackbar.LENGTH_SHORT).show();

                }
            } else {
                Snackbar.make(mFlash, "错误的条码", Snackbar.LENGTH_SHORT).show();

            }
        }else {
            Snackbar.make(mFlash, "错误的条码", Snackbar.LENGTH_SHORT).show();

        }
    }

    private void handleSignIn(BarCode barCode) {
        if (barCode.isRequireLogin() && !AppContext.getInstance().isLogin()) {
            showLogin();
            return;
        }
        showWaitDialog("正在签到...");
//        AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
//            @Override
//            public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
//                try {
//                    SingInResult res = SingInResult.parse(new String(arg2));
//                    if (res.isOk()) {
//                        DialogHelp.getMessageDialog(CaptureActivity.this, res.getMessage()).show();
//                    } else {
//                        DialogHelp.getMessageDialog(CaptureActivity.this, res.getErrorMes()).show();
//                    }
//                } catch (AppException e) {
//                    e.printStackTrace();
//                    onFailure(arg0, arg1, arg2, e);
//                }
//            }
//
//            @Override
//            public void onFailure(int arg0, Header[] arg1, byte[] arg2,
//                                  Throwable arg3) {
//                hideWaitDialog();
//                DialogHelp.getMessageDialog(CaptureActivity.this, arg3.getMessage()).show();
//            }
//
//            @Override
//            public void onFinish() {
//                super.onFinish();
//                hideWaitDialog();
//            }
//        };
//        OSChinaApi.singnIn(barCode.getUrl(), handler);
    }

    private void showLogin() {
        DialogHelp.getConfirmDialog(this, "请先登录，再进行", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
//                UIHelper.showLoginActivity(CaptureActivity.this);
            }
        }).show();
    }
    private void displayFrameworkBugMessageAndExit() {
        // camera error
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.app_name));
        builder.setMessage("相机打开出错，请稍后重试");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }

        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        builder.show();
    }

    public void restartPreviewAfterDelay(long delayMS) {
        if (handler != null) {
            handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
        }
    }

    private int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    private  android.support.v7.app.AlertDialog inputAlertDialog(String title, String message) {
        final EditText inputServer = new EditText(this);
        android.support.v7.app.AlertDialog.Builder dialog = new android.support.v7.app.AlertDialog.Builder(this);
           dialog
                .setTitle(title)
                .setMessage(message)
                .setView(inputServer)
                .setNeutralButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                String chkString = inputServer.getText()
                                        .toString();
                                if (!StringUtils.isEmpty(chkString)) {
                                    if ("车间工人".equals(userType)) {
                                        iv_count.setVisibility(View.GONE);
                                        UIHelper.showWorks(CaptureActivity.this,chkString);
                                    }else if ("仓库管理".equals(userType)){
                                        Snackbar.make(mFlash, "出入库不支持此功能", Snackbar.LENGTH_SHORT).show();
                                    }
                                }
                            }
                        });
        return  dialog.show();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.tv_sacan_faild:
                if (!StringUtils.isEmpty(userType)) {
                    if ("车间工人".equals(userType)) {
                        inputAlertDialog("输入Work号","输入派工单序号,如Work999-1");
                    }else if ("仓库管理".equals(userType)){
                        Snackbar.make(mFlash, "出入库不支持此功能", Snackbar.LENGTH_SHORT).show();
                    }else  if ("Administrator".equals(userType)){

                    }
                } else {
                    Snackbar.make(mFlash, "未定义的员工类型，没有任何操作功能", Snackbar.LENGTH_SHORT).show();
                }
                break;
            case R.id.capture_flash:

                break;
            case R.id.iv_count:
                if (StringUtils.isEmpty(workno)) {
                    if (cmps != null) {
                        if (cmps.size() > 0) {
                            String unScaned="";//没有扫描的
                            for (int k=0;k<cmps.size();k++){
                                CKComp ckComp= cmps.get(k);
                                if (!ckComp.isAll()){//代表该门相关的单全部扫描过了
                                    unScaned+="<p style=\"color:red\">"+"门编号："+ckComp.getItemDN()+"-"+leftMen(ckComp.getType())+"未扫描！"+"</p>";
                                }
                            }

                            if (StringUtils.isEmpty(unScaned)) {
//                                UIHelper.showRKDan(this, cmps);
                            }else {
                                android.support.v7.app.AlertDialog.Builder dialog = DialogHelp.getConfirmDialog1(this, unScaned, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {

                                    }
                                });
                                dialog.setTitle("下面还未扫描");
                                dialog.setCancelable(true);
                                dialog.show();
                                Snackbar.make(mFlash, "部分门还未全部扫描！", Snackbar.LENGTH_SHORT).show();
                            }
                        } else {
                            Snackbar.make(mFlash, "未扫描到任何入库信息", Snackbar.LENGTH_SHORT).show();
                        }
                    } else {
                        Snackbar.make(mFlash, "未扫描到任何入库信息", Snackbar.LENGTH_SHORT).show();
                    }
                }else {
                    if (cmps != null) {
                        if (cmps.size() > 0) {
                            String unScaned = "";//没有扫描的
                            for (int k = 0; k < cmps.size(); k++) {
                                CKComp ckComp = cmps.get(k);
                                if (!ckComp.isAll()) {//代表该门相关的单全部扫描过了
                                    unScaned += "<p style=\"color:red\">" + "门编号：" + ckComp.getItemDN() + "-" + leftMen(ckComp.getType()) + "未扫描！" + "</p>";
                                }
                            }

                            if (StringUtils.isEmpty(unScaned)) {
//                                UIHelper.showCKDan(this,checkedCKS, cmps);
                            } else {
                                android.support.v7.app.AlertDialog.Builder dialog = DialogHelp.getConfirmDialog1(this, unScaned, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {

                                    }
                                });
                                dialog.setTitle("下面还未扫描");
                                dialog.setCancelable(true);
                                dialog.show();
                                Snackbar.make(mFlash, "部分门还未全部扫描！", Snackbar.LENGTH_SHORT).show();
                            }
                        } else {
                            Snackbar.make(mFlash, "未扫描到任何出库信息", Snackbar.LENGTH_SHORT).show();
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    //判断还剩什么没有扫描
    private  String leftMen(String str){
        String mstr="";
        if ("zhu".equals(str)){
            mstr="副门";
        }else {
            mstr="主门";
        }
        return  mstr;
    }

    private boolean flag;

    @Override
    public void initView() {
        // TODO Auto-generated method stub

    }

    @Override
    public void initData() {
        // TODO Auto-generated method stub

    }
}